import serial
import time
import os
import sys
import random
import re
import datetime
# 定义常量
DEBUG_PORT = "COM4"
BAUDRATE = 115200
# 定义变量
debug_serial = None
#记录运行次数
runTimes		= 0
#log文件
DEBUG_LOG = ""

# 创建日志文件
def createLogFile():
    global DEBUG_LOG
    timestamp = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
    DEBUG_LOG = f"DEBUG_LOG_{timestamp}.log"
    
    # 创建日志文件时，指定编码为 utf-8
    with open(DEBUG_LOG, 'w', encoding='utf-8') as file:
        file.write("日志开始记录...\n")

# 日志写入函数
def write_log(log, logFile=""):
    # 打开文件时指定编码为 utf-8
    with open(logFile, 'a', encoding='utf-8') as file_object:
        file_object.write(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "\r\n" + log + "\r\n")
    print(log)


#发送at指令
def at_write(command, timeout, DEBUG_PORT_opened, at_result,RDY=0,CPIN=0):
 write_log(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())),DEBUG_LOG)
 at_command = command.encode("UTF-8")
 DEBUG_PORT_opened.write(at_command)

#读取at口返回
def at_read(serial_port, logFile=""):
 rec_str = ''
 while (True):
  time.sleep(1)
  lenth = serial_port.inWaiting()
  if lenth > 0:
   rec_str = serial_port.read(size=lenth)
   try:
    rec_str = re.sub('\\x1b.*?m', "", rec_str.decode("UTF-8"), 0, re.I)
    if logFile != "":
     with open(logFile, 'a') as file_object:
      rec_str = str(time.time()) + ":" + str(
       time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "\r\n" + rec_str
      file_object.write(
       str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "\r\n" + rec_str + "\r\n")
    return rec_str
   except:
    return ""
  else:
   break
 return rec_str

# 登录设备
def loginDevice():
 global DEBUG_LOG
 #确认登录失败的条件，或者，不可能失败
 while True:
  print("等待登录... ... ")
  time.sleep(3)
  at_write("\r\n",3,debug_serial,"OK")
  result = at_read(debug_serial)

  with open(DEBUG_LOG, 'a') as file_object:
   file_object.write(result)

  if "login:" in result:
   at_write("root\r\n",3,debug_serial,"OK")
   print("账号输入成功")
   time.sleep(2)
   at_write("oelinux123\r\n",3,debug_serial,"OK")
   print("密码输入成功")
  elif "~ #" in result:
   print("登录成功")
   break
  else:
   continue 

#检查debug口通信状态
def check_port_status():
 global debug_serial
 if debug_serial == None:
  try:
   debug_serial = serial.Serial(DEBUG_PORT,BAUDRATE)
  except:
   print("at口连接失败，请检查端口")
   sys.exit()

# 写入运行次数到日志
def writeRuntimesToLog():
 global runTimes
 with open(DEBUG_LOG, 'a+') as file_object:
  file_object.write("\r\n{} runtimes: {} {}\r\n".format("<"*20,runTimes,">"*20))
 print("\r\n{} runtimes: {} {}\r\n".format("<"*20,runTimes,">"*20))
 runTimes += 1
 
def get_gpio_state():
    at_write("cat /sys/kernel/debug/gpio | grep gpio77\r\n",3,debug_serial,"OK")
    result = at_read(debug_serial,DEBUG_LOG)
    try: 
        if "low" in result:
            return 0
        elif "high" in result:
            return 1
        else:
            print("未检测到GPIO77状态")
            return -1
    except Exception as e:
        print(str(e))
        return None, -1
    
    
# 拉低GPIO6
def pull_down_gpio6():
    at_write("echo 77 0 > /sys/kernel/debug/sleep/ql_lpm_pin\r\n",3,debug_serial,"OK")
    result = at_read(debug_serial,DEBUG_LOG)
    time.sleep(2)
# 重启模块
def reboot_modem():
    at_write("sys_reboot\r\n",3,debug_serial,"OK")
    time.sleep(70)
  
# 计算时间差
def calculate_time_diff(T1, T2):
    time_diff = datetime.datetime.strptime(T2, "%Y-%m-%d %H:%M:%S.%f") - datetime.datetime.strptime(T1, "%Y-%m-%d %H:%M:%S.%f")
    write_log(f"时间差: {time_diff.total_seconds()}秒", DEBUG_LOG)
    return time_diff.total_seconds()

# 主流程
def main():
    check_port_status()
    createLogFile()
    time_diffs = []  # 记录每次测试的时间差
    for i in range(10):
        #登录设备
        loginDevice()
        write_log(f"第{i+1}次测试开始", DEBUG_LOG)
        # 查询查询GPIO6默认为高电平
        get_gpio_state()
        # 拉低GPIO6并确认状态
        pull_down_gpio6()
        state = get_gpio_state()
        if state != 0:
            write_log("拉低GPIO6失败", DEBUG_LOG)
            continue
        # 重启
        write_log("开始重启模块", DEBUG_LOG)
        reboot_modem()
        write_log("模块重启完成", DEBUG_LOG)
        #登录设备
        loginDevice()
        T1 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        write_log(f"重启时间T1: {T1}", DEBUG_LOG)

        # 反复查询GPIO77直到恢复为高电平，并记录T2
        T2 = None
        while True:
            state = get_gpio_state()
            if state == 1:  # GPIO77恢复为高电平
                T2 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                write_log(f"恢复为高电平时间T2: {T2}", DEBUG_LOG)
                break
            time.sleep(0.001)  # 每0.001秒查询一次

        # 计算时间差
        if T1 and T2:
            time_diff = calculate_time_diff(T1, T2)
            time_diffs.append((T1, T2, time_diff))
        else:
            write_log("时间记录失败", DEBUG_LOG)

        write_log(f"第{i+1}次测试结束\n", DEBUG_LOG)
    
    # 输出数据统计结果
    write_log("数据统计结果:\n", DEBUG_LOG)
    for idx, (T1, T2, diff) in enumerate(time_diffs):
        write_log(f"第{idx+1}次: T1={T1}, T2={T2}, 差值={diff}秒", DEBUG_LOG)

    average_diff = sum([diff for _, _, diff in time_diffs]) / len(time_diffs)
    write_log(f"平均时间差: {average_diff}秒", DEBUG_LOG)
    write_log("测试结束", DEBUG_LOG)

    
if __name__ == '__main__':
     main()